package com.umpay.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Resource {
	private static Logger log = LoggerFactory.getLogger(Resource.class);
	public static InputStream loadResource(String path){
		log.info("path="+path);
		ClassLoader cl = Thread.currentThread().getContextClassLoader();
		InputStream in = cl.getResourceAsStream(path);
		log.info("in1="+in);
		
		if(null == in){
			in = ClassLoader.getSystemResourceAsStream(path);
			log.info("in2="+in);
		}
		if(null == in){
			String pt = getRealPath(path);
			try{
				in = new FileInputStream(pt);
			}catch(FileNotFoundException ex){
				log.warn(pt+"不存在");
			}
		}
		if(null == in)throw new RuntimeException("读取失败,path="+path);
		return in;
	}
	
	/**
	 * 获取资源的绝对路径
	 * @param path 包相对路径
	 * @return
	 */
	public static String getRealPath(String path){
		String str = Resource.class.getProtectionDomain().getCodeSource().getLocation().getPath();
		System.out.println(str);
		File f = new File(str);
		System.out.println(f.getAbsolutePath());
		return f.getAbsolutePath()+System.getProperty("file.separator")+path;
	}
	
	public static void main(String[] args) {
		String path="StdPayEtlServer_ehcache.xml";
		System.out.println(getRealPath(path));
		
	}
	
}
